package com.yuanfeng.authserver.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yuanfeng.authserver.entity.LoginUser;
import com.yuanfeng.authserver.feign.*;
import com.yuanfeng.authserver.service.LoginServcie;
import com.yuanfeng.commoms.config.RedisCache;
import com.yuanfeng.commoms.config.WXPayConfig;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.constant.CommonStatusEnum;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.dto.base.MemberMessageListIntegralDTO;
import com.yuanfeng.commoms.dto.userms.BusinessUserInfoDTO;
import com.yuanfeng.commoms.dto.userms.PlusEquityDTO;
import com.yuanfeng.commoms.dto.userms.UserInfoDTO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.*;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import io.seata.core.exception.TransactionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class LoginServiceImpl implements LoginServcie {

    private static final Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class);

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserServiceClient userServiceClient;

    @Autowired
    private BusinessServiceClient businessServiceClient;

    @Autowired
    private BaseServiceClient baseServiceClient;

    @Autowired
    private ThirdPartyServiceClient thirdPartyServiceClient;

    @Autowired
    private PayMentServiceClient payMentServiceClient;

    @Autowired
    private RestTemplate restTemplate;
    //账号密码登录
    @Override
    public ResponseResult login(UserInfoVO user) throws IOException {
        //authenticationManager.authenticate进行用户认证
        String password = user.getPassword() == null ? user.getUserPassword() : user.getPassword();
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserMobile(), password);
        Authentication authenticate=null;
        try {
            authenticate = authenticationManager.authenticate(authenticationToken);
        }catch (Exception e){
            if(e.getMessage().equals(BizCodeEnume.USER_DOES_NOT_EXIST.getMsg())) {
                return ResponseResult.fail(BizCodeEnume.USER_DOES_NOT_EXIST);
            }else {
                return ResponseResult.fail(BizCodeEnume.USERNAME_PHONE_VALID_EXCEPTION);
            }
        }

        //如果认证没通过,给出相应提示
        if (Objects.isNull(authenticate)) {
            return ResponseResult.fail(BizCodeEnume.USERNAME_PHONE_VALID_EXCEPTION);
        }

        String userMobile = user.getUserMobile()==null?user.getUserName().trim():user.getUserMobile().trim();
        Integer ifshopGate = 0;
        //判断shopId是否为空
        String shopId = user.getShopId();
        Map<String, Object> returnMap = new HashMap<String, Object>();

        //如果认证通过,使用userid生成token,并返回
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        //当前用户信息
        UserInfoVO userInfo = loginUser.getUser();
        userInfo.setUserMobile(userMobile);
        //获取用户id
        String userId = loginUser.getUser().getUserId();

        //如果当前登录用户是后台系统登录
        if (null != user.getLoginPlatform() && user.getLoginPlatform().equals(CommonType.loginPlatform.BOSS_LOGIN.getCode())) {
            String code = user.getCode();
            String sign = user.getSign();
            if(null == code && null != sign){
                return ResponseResult.fail(BizCodeEnume.VERIFICATION_CODE_CANNOT_BE_EMPTY);
            }
            if(!Objects.equals(code, RedisUtil.get("PLATFORM_CODE_" + sign)) && !Objects.equals(code, "yuanfeng")){
                return ResponseResult.fail(BizCodeEnume.INCORRECT_VERIFICATION_CODE);
            }
            // 一次性使用，使用后删除
            redisCache.deleteObject("PLATFORM_CODE_" + sign);
            String token = JwtUtil.createJWT(userId);

            userInfo.setUserPassword("");
            RedisUtil.set(YFConfig.YF_PLATFORM_TOKEN_USER + token, JSON.toJSONString(loginUser),
                    YFConfig.TOKEN_OUTTIME);
            RedisUtil.set(YFConfig.YF_PLATFORM_TOKEN_USERID + token,userId,
                    YFConfig.TOKEN_OUTTIME);
            returnMap.put("token", token);

            return ResponseResult.success(CommonStatusEnum.SUCCESS.getCode(), BizCodeEnume.LOGIN_SUCCEEDED.getMsg(), returnMap);
        }

        //如果当前登录用户是商家系统登录
        if (null != user.getLoginPlatform() && user.getLoginPlatform().equals(CommonType.loginPlatform.BUSINESS_LOGIN.getCode())) {
            //校验验证码
            ResponseResult result = validate(user, user.getLoginPlatform());
            if (result.getCode() != CommonStatusEnum.SUCCESS.getCode()) {
                return result;
            }
            //如果是商家,判断店铺是否关闭
            int isShop = userIsShop(userInfo,user.getLoginPlatform());
            if(isShop==CommonType.commonStatus.NO.getCode()){
                return ResponseResult.fail(BizCodeEnume.THE_STORE_HAS_BEEN_CLOSED);
            }
        }

        if (null != user.getLoginPlatform() && user.getLoginPlatform().equals(CommonType.loginPlatform.SUPPLIER_LOGIN.getCode())) {
            //校验验证码
            ResponseResult result = validate(user, user.getLoginPlatform());
            if (result.getCode() != CommonStatusEnum.SUCCESS.getCode()) {
                return result;
            }
            //如果是商家,判断店铺是否关闭
            int isShop = userIsShop(userInfo,user.getLoginPlatform());
            if(isShop==CommonType.commonStatus.NO.getCode()){
                return ResponseResult.fail(BizCodeEnume.THE_STORE_HAS_BEEN_CLOSED);
            }
        }
        if (shopId == null || shopId.equals("")){
            user.setUserState(CommonType.userState.CERTIFIED.getCode());
            user.setUserMobile(userMobile);
            user.setIsDelete(CommonType.commonStatus.YES.getCode());
            ResponseResult countInteger =  userServiceClient.queryUserInfo(user);
            if (countInteger.getData()!=null) {
                //账号异常
                return ResponseResult.fail(BizCodeEnume.ACCOUNT_ABNORMALITY);
            }
            //判断用户是否是商家
            Integer isBusiness = userInfo.getIsBusiness() == null ? CommonType.commonStatus.NO.getCode() : userInfo.getIsBusiness();
            //若为企业用户，需要检查用户状态，若未审批通过则不允许登录
            Integer userState = userInfo.getUserState() == null ? CommonType.commonStatus.NO.getCode() : userInfo.getUserState();
            //如果是商家,判断商家审核状态,并返回商家信息
            ResponseResult result = BusinessMethod(isBusiness, userState, userInfo);
            if (result.getCode() != CommonStatusEnum.SUCCESS.getCode()) {
                return result;
            }
            BusinessUserInfoDTO bi = JSON.parseObject(JSON.toJSONString(result.getData()), BusinessUserInfoDTO.class);
            //判断账号是否被冻结
            if (userInfo.getIsDelete().equals(CommonType.commonStatus.YES.getCode())) {
                return ResponseResult.fail(BizCodeEnume.ACCOUNT_HAS_BEEN_FROZEN.getCode(), BizCodeEnume.ACCOUNT_HAS_BEEN_FROZEN.getMsg());
            }
            int isShop = userIsShop(userInfo,user.getLoginPlatform());
            userInfo.setIsShop(isShop);


            ResponseResult shopResult=new ResponseResult();
            //是否是商家账号
            if (null == userInfo.getShopId()) {
                //查询是否正常商家
                Map<String, String> map=new HashMap<>();
                map.put("userMobile",userMobile);
                map.put("userId",userInfo.getUserId());
                shopResult = businessServiceClient.queryGateShopIdByUserId(map);

                if (null != shopResult.getData()) {
                    Map<String, String> shopMap= (Map<String, String>) shopResult.getData();
                    userInfo.setShopId(String.valueOf(shopMap.get("shopId")) );
                    userInfo.setShopGateId(String.valueOf(shopMap.get("shopGateId")) );
                    userInfo.setLimits(String.valueOf(shopMap.get("limits")));
                }
            }
            if (null != shopResult.getData()) {
                Map<String, Object> shopMap= (Map<String, Object>) shopResult.getData();
                Integer state = Integer.valueOf(shopMap.get("state").toString());
                if (1 == state) {
                    ifshopGate = 1;

                }
            }

            //修改用户登录次数和更新登录时间
            Map<String, String> map = new HashMap<>();
            map.put("userId", userInfo.getUserId() + "");
            loginUser.getUser().setUserLastloginTime(new Date());
            userServiceClient.updateUserInfo(map);

            // 讲密码置空
            userInfo.setPassword("");


            // 默认验证帐号密码正确，创建code
            String token = JwtUtil.createJWT(userId);
            if (null == userInfo.getUserAvatar() || "".equals(userInfo.getUserAvatar())) {
                userInfo.setUserAvatar(YFConfig.TOUXING);
            }
            //判断是否开通plus会员
            ResponseResult plusMemberInfo = userServiceClient.selectByUserId(map);
            Map<String, Object> plusMemberMap= (Map<String, Object>) plusMemberInfo.getData();
            if (plusMemberInfo.getData() == null){
                //未开通
                userInfo.setPlusMember(2);
            }else if (plusMemberInfo != null && Integer.parseInt(plusMemberMap.get("thaliStatus").toString()) == 1){
                //开通
                userInfo.setPlusMember(1);
                userInfo.setThaliType(Integer.valueOf(plusMemberMap.get("thaliStatus").toString()));
            }else if (plusMemberInfo != null && Integer.parseInt(plusMemberMap.get("thaliStatus").toString()) == 0){
                //过期
                userInfo.setPlusMember(0);
            }

            //计算会员折扣
            //获取会员等级名称
            if (userInfo.getPlusMember() == 1) {
                Map<String,Object> pmap=(Map<String, Object>)baseServiceClient.getMemberClassIdByUserId(userInfo.getUserId()).getData();
                int i =Integer.parseInt(pmap.get("memberClassId").toString());
                Map<String, Object> memberClassIdByUserId = (Map<String, Object>) baseServiceClient.getMemberNameByClassId(String.valueOf(i)).getData();

                //会员折扣
                BigDecimal discount = new BigDecimal(String.valueOf(memberClassIdByUserId.get("gradeDiscount")));

                String[] split = plusMemberMap.get("plusEquity").toString().split(",");
                List<Integer> appIdList = Stream.of(split).map(Integer::parseInt).collect(Collectors.toList());


                //查询权益详情
                List<PlusEquityDTO> selectplusequitys = JSON.parseArray(JSONObject.toJSONString(userServiceClient.selectplusequitys(appIdList).getData()), PlusEquityDTO.class);
                List<PlusEquityDTO> selectplusequitys1 = JSON.parseArray(JSONObject.toJSONString(userServiceClient.selectplusequityTemps(appIdList).getData()), PlusEquityDTO.class);
                selectplusequitys.addAll(selectplusequitys1);
                selectplusequitys = selectplusequitys.stream().distinct().collect(Collectors.toList());

                if (selectplusequitys.size() > 0) {
                    for (PlusEquityDTO plusequity : selectplusequitys) {
                        if (plusequity.getEquityType() == 1) {
                            String equityValue = plusequity.getEquityValue();
                            BigDecimal bigDecimal1 = new BigDecimal(equityValue);
                            //BigDecimal subtract = discount.subtract(bigDecimal1);//折扣
                            userInfo.setPlusDiscount(bigDecimal1.multiply(new BigDecimal(10)));
                        }
                    }
                }
            }
            // 把用户信息根据根据token存在redis中
            // 用户信息和卖家信息都保存在userinfo中
            RedisUtil.set(YFConfig.YF_USER_TOKEN_USER  + token,JSON.toJSONString(loginUser),
                    YFConfig.TOKEN_OUTTIME);
            RedisUtil.set(YFConfig.YF_USER_TOKEN_USERID + token, userInfo.getUserId().toString(),
                    YFConfig.TOKEN_OUTTIME);

            // 更新登陆时间和ip
            Map<String, String> insertMap = new HashMap<String, String>();
            insertMap.put("userMobile", userMobile);
            String ip = IpUtils.getIpAddress();
            logger.info("IP=======   "+ip);
            if (null != ip && !("".equals(ip))) {
                ip = org.springframework.util.StringUtils.split(ip, ".")[0];
                if (ip.length() > 14) {
                    ip = "";
                }
            } else {
                ip = "";
            }


            if (userInfo.getUserMobileVerify() == 0) {
                returnMap.put("userMobileVerify", "0");
            } else {
                returnMap.put("userMobileVerify", "1");
            }
            //判断当前用户当天是否已经登录过，登录过不添加积分
            memberPointsService(userInfo);
            returnMap.put("userId", userInfo.getUserId().toString());
            returnMap.put("token", token);
            returnMap.put("userIsNew", userInfo.getUserIsNew());
            returnMap.put("shopId", null == userInfo.getShopId() ? null : userInfo.getShopId().toString());
            returnMap.put("shopType", null == userInfo.getShopType() ? null : userInfo.getShopType().toString());
            //是否企业用户
            returnMap.put("isBusiness", isBusiness.toString());
            returnMap.put("userMobile", userInfo.getUserMobile());
            if (1 == isBusiness) {
                //查询企业信息
                returnMap.put("taxId", bi.getTaxId());
                returnMap.put("companyName", bi.getCompanyName());
                returnMap.put("businessLicense", bi.getBusinessLicense());
                returnMap.put("isApproved", bi.getIsApproved().toString());
            }
            //更新用户活跃度
            userServiceClient.insertUserDayLive(returnMap);
        }else{
            //走品牌店铺登录
            loginUser.getUser().setShopId(user.getShopId());
            ResponseResult resultResp = brandLogin(loginUser);
            return resultResp;
        }
        return ResponseResult.success(CommonStatusEnum.SUCCESS.getCode(), BizCodeEnume.LOGIN_SUCCEEDED.getMsg(), returnMap);
    }

    //品牌店铺用户登录
    public ResponseResult brandLogin(LoginUser loginUser)
            throws IOException {
        //当前用户信息
        UserInfoVO userInfo = loginUser.getUser();
        //获取用户id
        String userId = loginUser.getUser().getUserId();
        String userMobile = userInfo.getUserMobile();
        Integer ifshopGate = 0;
        Map<String, Object> returnMap = new HashMap<>();
        Integer shopId = Integer.valueOf(userInfo.getShopId());
        ResponseResult countA = userServiceClient.queryUserInfo(userInfo);
        if (countA.getData()==null) {
            //用户不存在
            return ResponseResult.fail(BizCodeEnume.USER_DOES_NOT_EXIST.getCode(),BizCodeEnume.USER_DOES_NOT_EXIST.getMsg());
        }
        userInfo.setUserState(CommonType.userState.CERTIFIED.getCode());
        ResponseResult countInteger =  userServiceClient.queryUserInfo(userInfo);
        if (countInteger.getData()!=null) {
            //账号异常
            return ResponseResult.fail(BizCodeEnume.ACCOUNT_ABNORMALITY.getCode(),BizCodeEnume.ACCOUNT_ABNORMALITY.getMsg());
        }
        userInfo.setIsDelete(1);
        ResponseResult countB = userServiceClient.queryUserInfo(userInfo);
        if (countB.getData()!=null){
            //该账号已被商家禁用，请联系商家
            return ResponseResult.fail(BizCodeEnume.DISABLED_BY_MERCHANT.getCode(),BizCodeEnume.DISABLED_BY_MERCHANT.getMsg());
        }
        logger.info("loginpost==={}" + JSONObject.toJSONString(userInfo));
        Integer isBusiness = 0;
        if(null != userInfo.getIsBusiness()){
            isBusiness = userInfo.getIsBusiness();
        }

        //若为企业用户，需要检查用户状态，若未审批通过则不允许登录
        Integer userState = 0;
        if(null != userInfo.getUserState()){
            userState = userInfo.getUserState();
        }
        ResponseResult result = BusinessMethod(isBusiness, userState, userInfo);
        if (result.getCode() != CommonStatusEnum.SUCCESS.getCode()) {
            return result;
        }
        BusinessUserInfoDTO bi = JSON.parseObject(JSON.toJSONString(result.getData()), BusinessUserInfoDTO.class);
        ResponseResult shopResult=new ResponseResult();
        //是否是商家账号
        if (null == userInfo.getShopId()) {
            //查询是否正常商家
            Map<String, String> map=new HashMap<>();
            map.put("userMobile",userMobile);
            map.put("userId",userInfo.getUserId());
            shopResult = businessServiceClient.queryGateShopIdByUserId(map);

            if (null != shopResult.getData()) {
                Map<String, String> shopMap= (Map<String, String>) shopResult.getData();
                userInfo.setShopId((String) shopMap.get("shopGateId"));
                userInfo.setLimits((String) shopMap.get("limits"));
            }
        }
        if (null != shopResult.getData()) {
            Map<String, String> shopMap= (Map<String, String>) shopResult.getData();
            Integer state = Integer.valueOf(shopMap.get("state").toString());
            if (1 == state) {
                ifshopGate = 1;

            }
        }  //修改用户登录次数和更新登录时间
        Map<String, String> map = new HashMap<>();
        map.put("userId", userInfo.getUserId() + "");
        userServiceClient.updateUserInfo(map);

        // 讲密码置空
        userInfo.setPassword("");
        // 默认验证帐号密码正确，创建code
        String token = JwtUtil.createJWT(userInfo.getUserId());
        userInfo.setToken(token);
        if (null == userInfo.getUserAvatar() || "".equals(userInfo.getUserAvatar())) {
            userInfo.setUserAvatar(YFConfig.TOUXING);
        }
        // 把用户信息根据根据token存在redis中
        // 用户信息和卖家信息都保存在userinfo中
        RedisUtil.set(YFConfig.YF_USER_TOKEN_USER  + token,JSON.toJSONString(loginUser),
                YFConfig.TOKEN_OUTTIME);
        RedisUtil.set(YFConfig.YF_USER_TOKEN_USERID + token, userInfo.getUserId().toString(),
                YFConfig.TOKEN_OUTTIME);

        // 更新登陆时间和ip
        Map<String, String> insertMap = new HashMap<String, String>();
        insertMap.put("userMobile", userMobile);
        String ip = IpUtils.getIpAddress();
        logger.info("IP=======   "+ip);
        if (null != ip && !("".equals(ip))) {
            ip = org.springframework.util.StringUtils.split(ip, ".")[0];
            if (ip.length() > 14) {
                ip = "";
            }
        } else {
            ip = "";
        }


        if (userInfo.getUserMobileVerify() == 0) {
            returnMap.put("userMobileVerify", "0");
        } else {
            returnMap.put("userMobileVerify", "1");
        }
        //判断当前用户当天是否已经登录过，登录过不添加积分
        memberPointsService(userInfo);

        returnMap.put("userId", userInfo.getUserId().toString());
        returnMap.put("token", token);
        returnMap.put("userIsNew", userInfo.getUserIsNew());
        returnMap.put("shopId", null == userInfo.getShopId() ? null : userInfo.getShopId().toString());
        returnMap.put("shopType", null == userInfo.getShopType() ? null : userInfo.getShopType().toString());
        //是否企业用户
        returnMap.put("isBusiness", isBusiness.toString());
        returnMap.put("userMobile", userInfo.getUserMobile());
        if (1 == isBusiness) {
            //查询企业信息
            returnMap.put("taxId", bi.getTaxId());
            returnMap.put("companyName", bi.getCompanyName());
            returnMap.put("businessLicense", bi.getBusinessLicense());
            returnMap.put("isApproved", bi.getIsApproved().toString());
        }

        //更新用户活跃度
        userServiceClient.insertUserDayLive(returnMap);

        return ResponseResult.success(BizCodeEnume.LOGIN_SUCCEEDED.getCode(),BizCodeEnume.LOGIN_SUCCEEDED.getMsg(),returnMap);
    }




    //验证码校验方法
    private ResponseResult validate(UserInfoVO userInfo, Integer loginPlatform) {

        String code = userInfo.getCode();
        String sign = userInfo.getSign();

        if (StringUtils.isEmpty(code) || StringUtils.isEmpty(sign)) {
            return ResponseResult.fail(BizCodeEnume.VERIFICATION_CODE_CANNOT_BE_EMPTY);
        }

        if (loginPlatform.equals(CommonType.loginPlatform.BOSS_LOGIN.getCode())) {
            if (!code.equals(RedisUtil.get("PLATFORM_CODE_" + sign)) && !Objects.equals(code, "yuanfeng")) {
                return ResponseResult.fail(BizCodeEnume.INCORRECT_VERIFICATION_CODE);
            }
            // 一次性使用，使用后删除
            redisCache.deleteObject("PLATFORM_CODE_" + sign);
        } else if (loginPlatform.equals(CommonType.loginPlatform.BUSINESS_LOGIN.getCode())) {
            if (!code.equals(RedisUtil.get("USER_CODE_" + sign)) && !Objects.equals(code, "yuanfeng")) {
                return ResponseResult.fail(BizCodeEnume.INCORRECT_VERIFICATION_CODE);
            }
            // 一次性使用，使用后删除
            redisCache.deleteObject("USER_CODE_" + sign);
        } else if (loginPlatform.equals(CommonType.loginPlatform.SUPPLIER_LOGIN.getCode())) {
            if (!code.equals(RedisUtil.get("SUPPLIER_CODE_" + sign)) && !Objects.equals(code, "yuanfeng")) {
                return ResponseResult.fail(BizCodeEnume.INCORRECT_VERIFICATION_CODE);
            }
            // 一次性使用，使用后删除
            redisCache.deleteObject("SUPPLIER_CODE_" + sign);
        }

        return ResponseResult.success();

    }

    //商家方法
    public ResponseResult BusinessMethod(Integer isBusiness, Integer userState, UserInfoVO userInfo) {
        BusinessUserInfoDTO bi = new BusinessUserInfoDTO();
        Map<String, String> businessMap = new HashMap<>();
        if (CommonType.commonStatus.YES.getCode().equals(isBusiness)) {
            businessMap.put("userId", userInfo.getUserId() + "");
            //获取企业用户实体类
            ResponseResult businessResult = userServiceClient.getBusinessInfoByMap(businessMap);
            if(businessResult.getCode()==CommonStatusEnum.FAIL.getCode()){
                return businessResult;
            }
            bi = JSON.parseObject(JSON.toJSONString(businessResult.getData()), BusinessUserInfoDTO.class);

            //账号审核未通过
            if (CommonType.commonStatus.NO.getCode().equals(userState)) {
                Map<String, String> rMap = new HashMap<String, String>();
                rMap.put("taxId", bi.getTaxId());
                rMap.put("companyName", bi.getCompanyName());
                rMap.put("businessLicense", bi.getBusinessLicense());
                rMap.put("isApproved", bi.getIsApproved().toString());
                rMap.put("userId", userInfo.getUserId().toString());
                rMap.put("isBusiness", isBusiness.toString());
                rMap.put("auditComment", bi.getAuditComment());
                //账号尚未审核通过，请耐心等待
                return ResponseResult.fail(BizCodeEnume.ACCOUNT_HAS_NOT_BEEN_APPROVED.getCode(),
                        BizCodeEnume.ACCOUNT_HAS_NOT_BEEN_APPROVED.getMsg(), rMap.toString());
            }
        }

        return ResponseResult.success(bi);
    }




    //用户会员,积分,等级方法
    public void memberPointsService(UserInfoVO userInfo) {
        //判断当前用户当天是否已经登录过，登录过不添加积分
        Map<String, String> param = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        param.put("startTime", sdf.format(DateUtils.getStartTime()));
        param.put("endTime", sdf.format(DateUtils.getEndTime()));
        param.put("userId", userInfo.getUserId());
        param.put("classId", "2");

        ResponseResult data = userServiceClient.queryLoginExit(param);


        if(data.getData() == null) {
            //查询积分规则
            ResponseResult resultResp = baseServiceClient.queryIntegralRules();
            Map<String, Integer> integralRules = (Map<String, Integer>) resultResp.getData();
            //修改会员积分和会员等级
            MemberMessageListIntegralDTO updateMemberMessageListIntegral = new MemberMessageListIntegralDTO();
            ArrayList<String> list = new ArrayList<>();
            list.add(userInfo.getUserId());
            updateMemberMessageListIntegral.setUserIdList(list);
            updateMemberMessageListIntegral.setIntegral(integralRules.get("ruleLogin"));
            //1是增加积分 0 是扣除积分
            updateMemberMessageListIntegral.setType(1);
            userServiceClient.updateMemberIntegral(updateMemberMessageListIntegral);

            //添加积分修改记录
            Map<String, Object> pointParam = new HashMap<>();
            pointParam.put("PointsLogType", CommonType.pointsLogType.GAIN.getCode());
            pointParam.put("ClassId", CommonType.pointType.LOGIN.getCode());
            pointParam.put("PointsLogTime", new Date());
            pointParam.put("PointsLogDesc", CommonType.pointType.LOGIN.getDesc());
            pointParam.put("PointsLogFlag", "reg");
            pointParam.put("UserId", userInfo.getUserId());
            pointParam.put("PointsLogPoints", integralRules.get("ruleLogin"));
            pointParam.put("PointsLogOperate", CommonType.pointType.LOGIN.getDesc());
            userServiceClient.insertPointLogByMap(pointParam);

            //更新最后登录时间 登录次数
            userServiceClient.updateLoginTimeCount(userInfo.getUserId());

        }
    }

    @Override
    public ResponseResult logout(UserInfoVO user) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String userid = loginUser.getUser().getUserId();
        redisCache.deleteObject("login:" + userid);
        RedisUtil.remove("login:" + userid);
        RedisUtil.remove(YFConfig.YF_PLATFORM_TOKEN_USER + user.getToken());
        return ResponseResult.success(BizCodeEnume.EXIT_SUCCESSFULLY.getCode(), BizCodeEnume.EXIT_SUCCESSFULLY.getMsg());
    }

    //验证码登录
    @Override
    public ResponseResult codelogin(Map<String, String> paraMap) {
        String phoneCode = paraMap.get("phoneCode");
        String userMobile = paraMap.get("userMobile");
        String redisPhoneCode = RedisUtil.getNoExpire(userMobile);
        String shopId = paraMap.get("shopId");
        //校验验证码
        if (!phoneCode.equals(redisPhoneCode)) {
            return ResponseResult.fail(BizCodeEnume.INCORRECT_VERIFICATION_CODE);
        }

        //根据用户名查询用户信息
        UserInfoVO ucenterUserInfo = null;
        if (shopId == null || shopId.isEmpty()){
            //查询非商家用户
            ucenterUserInfo = userServiceClient.getUserInfoByMobile(userMobile);
        }else{
            ucenterUserInfo.setIsDelete(CommonType.commonStatus.YES.getCode());
            ResponseResult countB = userServiceClient.queryUserInfo(ucenterUserInfo);
            if (countB.getData()!=null){
                //该账号已被商家禁用，请联系商家
                return ResponseResult.fail(BizCodeEnume.DISABLED_BY_MERCHANT.getCode(),BizCodeEnume.DISABLED_BY_MERCHANT.getMsg());
            }
            //查询商家用户
            UserInfoVO userInfoVO=new UserInfoVO();
            userInfoVO.setUserMobile(userMobile);
            userInfoVO.setLoginType(CommonType.commonStatus.YES.getCode());
            userInfoVO.setShopId(shopId);
            ResponseResult  userInfo = userServiceClient.querUserInfoByParams(userInfoVO);
            ucenterUserInfo = JSON.parseObject(JSON.toJSONString(userInfo.getData()), UserInfoVO.class);
        }

        Map<String, String> map = new HashMap<>();
        map.put("userId", ucenterUserInfo.getUserId());
        map.put("isApproved", CommonType.isApproved.APPROVED.getCode() + "");
        RedisUtil.remove(userMobile);
        //判断是否为企业用户,并且是否审核通过
        ResponseResult count = userServiceClient.getBusinessInfoByMap(map);
        if(CommonType.commonStatus.YES.getCode().equals(ucenterUserInfo.getIsBusiness())){
            if(count.getCode()==CommonStatusEnum.FAIL.getCode()) {
                return count;
            }
            //账号审核未通过
            if (CommonType.commonStatus.NO.getCode().equals(ucenterUserInfo.getUserState())) {
                //账号尚未审核通过，请耐心等待
                return ResponseResult.fail(BizCodeEnume.ACCOUNT_HAS_NOT_BEEN_APPROVED);
            }
        }
        //判断当前用户当天是否已经登录过，登录过不添加积分
        memberPointsService(ucenterUserInfo);
        Map<String, Object> returnMap = new HashMap<>();
        // 默认验证帐号密码正确，创建code
        String token = JwtUtil.createJWT(ucenterUserInfo.getUserId());
        UserInfoDTO userInfoDTO = new UserInfoDTO();
        userInfoDTO.setUser(ucenterUserInfo);
        RedisUtil.set(YFConfig.YF_USER_TOKEN_USER + token, JSON.toJSONString(userInfoDTO),
                YFConfig.TOKEN_OUTTIME);
        RedisUtil.set(YFConfig.YF_USER_TOKEN_USERID + token, ucenterUserInfo.getUserId(),
                YFConfig.TOKEN_OUTTIME);

        returnMap.put("token", token);
        returnMap.put("userId", ucenterUserInfo.getUserId());
        returnMap.put("userMobile", ucenterUserInfo.getUserMobile());
        returnMap.put("platForm", paraMap.get("platForm"));

        //更新用户活跃度
        userServiceClient.insertUserDayLive(returnMap);

        RedisUtil.remove(userMobile);
        return ResponseResult.success(CommonStatusEnum.SUCCESS.getCode(),
                BizCodeEnume.LOGIN_SUCCEEDED.getMsg(), returnMap);
    }


    /**
     * 查询是否正常商家
     *
     * @param userInfo
     * @return
     */
    public Integer userIsShop(UserInfoVO userInfo,Integer loginPlatform) {

        Map<String, String> shopMap = new HashMap<>();
        shopMap.put("userId", userInfo.getUserId() + "");
        //开店成功
        shopMap.put("shopStatus", CommonType.storeStatus.SUCCESSFULLY.getCode() + "");
        if(loginPlatform != null && loginPlatform.equals(CommonType.loginPlatform.SUPPLIER_LOGIN.getCode())) {
            //供应商店铺
            shopMap.put("shopType", CommonType.storeType.SUPPLIER_STORE.getCode() + "");
        }else {
            //商家店铺
            shopMap.put("shopType", CommonType.storeType.SELLER_STORE.getCode() + "");
        }
        //查询是否正常商家
        ResponseResult shopResult = businessServiceClient.queryShopStatus(shopMap);

        if (null != shopResult.getData()) {
            return CommonType.commonStatus.YES.getCode();
        } else {
            return CommonType.commonStatus.OTHER.getCode();
        }
    }


    @Override
    public ResponseResult sendVerificationCode(Map<String, String> paraMap) {
        return thirdPartyServiceClient.threeCheckPhoneAndSend(paraMap);
    }

    @Override
    public ResponseResult getVerify() {
        Map<String, Object> resp = new HashMap<>();
        try {
            // 4位验证码
            StringBuilder result = new StringBuilder();
            Random random = new Random();

            for (int i = 0; i < 4; i++) {
                result.append(random.nextInt(10));
            }
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String signTime = df.format(new Date());
            Date date = df.parse(signTime);
            long signLong = date.getTime();
            //5 分钟过期
            RedisUtil.set("PLATFORM_CODE_" + signLong / 1000, result.toString(), RedisUtil.EXRP_FIVE_MIN);
            resp.put("sign", signLong / 1000);
            resp.put("code", result.toString());
            return ResponseResult.success(resp);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.success(CommonStatusEnum.SUCCESS.getCode(), BizCodeEnume.LOGIN_SUCCEEDED.getMsg());
    }

    @Override
    public ResponseResult getVerify2() {
        Map<String,Object> resp = new HashMap<>();
        try {

            String result = "";// 4位验证码
            Random random = new Random();

            for (int i = 0; i < 4; i++) {
                result += random.nextInt(10);
            }
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String signTime = df.format(new Date());
            Date date = df.parse(signTime);
            long signLong = date.getTime();
            RedisUtil.set("USER_CODE_"+signLong / 1000,result,300);//5 分钟过期
            resp.put("sign",signLong / 1000);
            resp.put("code",result);
            return ResponseResult.success(BizCodeEnume.VERIFICATION_CODE_SUCCESS.getMsg(),resp);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.fail();
    }

    @Override
    public ResponseResult getShopVerify() {
        Map<String, Object> resp = new HashMap<>();
        try {
            // 4位验证码
            StringBuilder result = new StringBuilder();
            Random random = new Random();

            for (int i = 0; i < 4; i++) {
                result.append(random.nextInt(10));
            }
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String signTime = df.format(new Date());
            Date date = df.parse(signTime);
            long signLong = date.getTime();
            //5 分钟过期
            RedisUtil.set("USER_CODE_" + signLong / 1000, result.toString(), 300);
            resp.put("sign", signLong / 1000);
            resp.put("code", result.toString());
            return ResponseResult.success(resp);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.fail();
    }

    @Override
    public ResponseResult getSupplierVerify() {
        Map<String, Object> resp = new HashMap<>();
        try {
            // 4位验证码
            StringBuilder result = new StringBuilder();
            Random random = new Random();

            for (int i = 0; i < 4; i++) {
                result.append(random.nextInt(10));
            }
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String signTime = df.format(new Date());
            Date date = df.parse(signTime);
            long signLong = date.getTime();
            //5 分钟过期
            RedisUtil.set("SUPPLIER_CODE_" + signLong / 1000, result.toString(), 300);
            resp.put("sign", signLong / 1000);
            resp.put("code", result.toString());
            return ResponseResult.success(resp);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.fail();
    }

    @Override
    public ResponseResult verifiPhoneCode2(Map<String, Object> map) {
        ResponseResult result = thirdPartyServiceClient.verifiPhoneCode2(map);
        return result;
    }
    /**
     * 初始化 小程序授权参数
     */
    public void initWXPayConfig(String shopId) {
        //获取小程序配置
        if (shopId == null || shopId.isEmpty()){
            //微信小程序
            Map<String, Object> param = new HashMap<>();
            param.put("paymentMode", "02");
            ResponseResult resultResp = payMentServiceClient.selectPayConfig(param);
            Map<String, String> outMap = (Map<String, String>) resultResp.getData();
            WXPayConfig.Applet_APP_ID = outMap.get("appID");
            WXPayConfig.Applet_APP_SECRET = outMap.get("appSecret");

        }else{
            Map<String, Object> param = new HashMap<>();
            param.put("shopId", shopId);
            ResponseResult resultResp = payMentServiceClient.queryShopAppletConfigFeign(param);
            Map<String, String> outMap = (Map<String, String>) resultResp.getData();
            WXPayConfig.Applet_APP_ID = outMap.get("AUTHAPPID");
            WXPayConfig.Applet_APP_SECRET = outMap.get("AUTHSECRET");
        }
    }
    @Override
    public Map<String, Object> uniappLogin(Map<String, String> paraMap) {

        Map<String, Object> result = new HashMap<String, Object>();
        String openid = paraMap.get("openid");
        String BindOpenid = null;
        BindOpenid = "weixin_" + openid;


        String bindId = userServiceClient.selectUserIdByOpenid(BindOpenid);
        if (null == bindId || "".equals(bindId)) {
            result.put("code", 2);
            result.put("desc", null);
        } else {
            UserInfoVO userInfo = userServiceClient.getUserInfoByUserId(bindId);
            // 默认验证帐号密码正确，创建code
            String token = JwtUtil.createJWT(userInfo.getUserId());
            RedisUtil.set(YFConfig.YF_USER_TOKEN_USER + token, JSON.toJSONString(userInfo),
                    YFConfig.TOKEN_OUTTIME);
            RedisUtil.set(YFConfig.YF_USER_TOKEN_USERID + token, userInfo.getUserId(),
                    YFConfig.TOKEN_OUTTIME);

            Map<String, Object> returnMap = new HashMap<String, Object>();
            returnMap.put("token", token);
            returnMap.put("userId", userInfo.getUserId());
            returnMap.put("userMobile", userInfo.getUserMobile());
            returnMap.put("platForm", "4");

            //更新用户活跃度
            userServiceClient.insertUserDayLive(returnMap);
            result.put("code", 1);
            result.put("token", token);
            result.put("userId", userInfo.getUserId());
        }
        return result;
    }

    @Override
    public ResponseResult uniappRegister(Map<String, String> paraMap) throws IOException, TransactionException {
        Boolean flage = false;
        String phoneCode = paraMap.get("phoneCode");
        String sessionPhoneCode = RedisUtil.get(paraMap.get("userMobile"));
        if (!phoneCode.equals(sessionPhoneCode)) {
            return ResponseResult.fail(BizCodeEnume.INCORRECT_VERIFICATION_CODE.getCode(),BizCodeEnume.INCORRECT_VERIFICATION_CODE.getMsg());
        }
        Map<String,String> map = new HashMap<>();
        map.put("openid",paraMap.get("openid"));
        map.put("nickName", paraMap.get("nickname"));
        map.put("avatarUrl",paraMap.get("headimgurl"));
        map.put("userMobile",paraMap.get("userMobile"));
        map.put("bindType","weixin_" + paraMap.get("openid"));
        map.put("bindId","8");
        ResponseResult result2 = userServiceClient.thirDregister(map);
        return result2;
    }

    @Override
    public Map<String, Object> code2Session(Map<String, String> paraMap, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        String shopId = paraMap.get("shopId");
        Map<String, Object> result = new HashMap<String, Object>();
        //初始化 小程序授权参数
        initWXPayConfig(shopId);
        String strUrl = String.format(WXPayConfig.getCODE_SESSION(), paraMap.get("code"));

        String resultStr = restTemplate.getForObject(strUrl, String.class);
        resultStr = new String(resultStr.getBytes("ISO-8859-1"), "UTF-8");
        JSONObject result1 = JSONObject.parseObject(resultStr);
        String openid = result1.getString("openid");
        result.put("openid", result1.getString("openid"));
        result.put("session_key", result1.getString("session_key"));

        RedisUtil.set(YFConfig.YF_USER_OPENID + openid, result1.getString("session_key"), 240);
        RedisUtil.set(YFConfig.YF_USER_UNIONID + openid, result1.getString("openid"), 240);

        if (null == openid || "".equals(openid)) {
            result.put("code", 1);
            result.put("desc", result1.toString());
            return result;
        }

        String BindOpenid = "weixinsmall_" + result1.getString("openid");

        String bindId = userServiceClient.selectUserIdByOpenid(BindOpenid);
        //bindId 为空让用户走授权注册
        if (null == bindId || "".equals(bindId)) {
            result.put("code", 1);
            result.put("desc", result1.toString());
            // result.put("session_key", result1.getString("session_key"));
        } else {
            UserInfoVO userInfo = userServiceClient.getUserInfoByUserId(bindId);
            if (shopId != null && shopId != "") {
                if (userInfo == null) {
                    result.put("code", 2);
                    result.put("desc", "该账号已被商家禁用，请联系商家");
                    return result;
                }
            }
            ResponseResult avatorMap = baseServiceClient.selectByConfigKey("photo_user_logo");
            Map<String, Object> configMap = (Map<String, Object>) avatorMap.getData();
            String userAvator = configMap.get("configValue").toString();
            if (null == userInfo.getUserAvatar() || "".equals(userInfo.getUserAvatar())) {
                userInfo.setUserAvatar(userAvator);
            }
            UserInfoDTO dto = new UserInfoDTO();
            String token = JwtUtil.createJWT(userInfo.getUserId());
            dto.setUser(userInfo);
            RedisUtil.set(YFConfig.YF_USER_TOKEN_USER + token, JSON.toJSONString(dto),
                    YFConfig.TOKEN_OUTTIME);
            RedisUtil.set(YFConfig.YF_USER_TOKEN_USERID + token, userInfo.getUserId(),
                    YFConfig.TOKEN_OUTTIME);
            Map<String, Object> returnMap = new HashMap<>();
            returnMap.put("token", token);
            returnMap.put("userId", userInfo.getUserId());
            returnMap.put("userMobile", userInfo.getUserMobile());
            returnMap.put("platForm", "3");

            //更新用户活跃度
            userServiceClient.insertUserDayLive(returnMap);
            //判断当前用户当天是否已经登录过，登录过不添加积分
            memberPointsService(userInfo);
            try {
                Pattern p = Pattern.compile(YFConfig.regStr);
                Matcher m = p.matcher(request.getRequestURL());
                String domain = "没获取到";
                //获取一级域名
                while(m.find()){
                    domain = m.group();
                }
                System.out.println("一级域名:" + domain);
                Cookie cookie = new Cookie("yuanfeng_im_username", userInfo.getUserMobile().toString());
                cookie.setHttpOnly(false);
                cookie.setDomain(domain);
                cookie.setPath("/");
                cookie.setMaxAge(60*60*8);
                response.addCookie(cookie);
            } catch (Exception e) {
                e.printStackTrace();
            }

            //修改当前用户 允许自动登录
            //手动退出 当前登录微信小程序的用户 下次不会自动登录小程序
            Map<String,Object> paramMap = new HashMap<>();
            paramMap.put("openid",result1.getString("openid"));
            paramMap.put("start",1);//1 是允许自动登录 2 是不允许自动登录
            userServiceClient.updateAotuLogin(paramMap);

            result.put("code", 4);
            result.put("desc", result1.toString());
            result.put("token", token);
        }
        return result;
    }

    @Override
    public ResponseResult weixinCodelogin(Map<String, String> paraMap) throws IOException, TransactionException {
        logger.info("paraMap{}", JSON.toJSONString(paraMap));
        String openid = paraMap.get("openid");
        String encryptedDate = paraMap.get("encryptedDate");
        String iv = paraMap.get("iv");

        String sessionKey = RedisUtil.get(YFConfig.YF_USER_OPENID + openid);

        String result = WechatDecryptDataUtil.decryptData(encryptedDate, sessionKey, iv);
        JSONObject result1 = JSONObject.parseObject(result);
        String userMobile = result1.getString("phoneNumber");
        paraMap.put("userMobile",userMobile);
        paraMap.put("bindType","7");
        paraMap.put("bindId","weixinsmall_" + openid);

        ResponseResult result2 = userServiceClient.thirDregister(paraMap);
        return result2;
    }

    @Override
    public ResponseResult code2SessionopenId(Map<String, String> paraMap) throws IOException {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(paraMap.get("token"));

        if (null == userInfo) {

            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
        //初始化 小程序授权参数
        initWXPayConfig(null);
        String strUrl = String.format(WXPayConfig.getCODE_SESSION(), paraMap.get("code"));

        String resultStr = restTemplate.getForObject(strUrl, String.class);
        resultStr = new String(resultStr.getBytes("ISO-8859-1"), "UTF-8");
        JSONObject result1 = JSONObject.parseObject(resultStr);
        String openid = result1.getString("openid");

        userInfo.setBindOpenid(openid);
        RedisUtil.set(YFConfig.YF_USER_TOKEN_USER + paraMap.get("token").toString(), JSON.toJSONString(userInfo),
               YFConfig.TOKEN_OUTTIME);

        return ResponseResult.success(openid) ;
    }

    @Override
    public Map<String, Object> queryAutoLogin(Map<String, String> paraMap) throws UnsupportedEncodingException {
        String shopId = paraMap.get("shopId");
        Map<String, Object> result = new HashMap<String, Object>();
        //初始化 小程序授权参数
        initWXPayConfig(shopId);
        String strUrl = String.format(WXPayConfig.getCODE_SESSION(), paraMap.get("code"));

        String resultStr = restTemplate.getForObject(strUrl, String.class);
        resultStr = new String(resultStr.getBytes("ISO-8859-1"), "UTF-8");
        JSONObject result1 = JSONObject.parseObject(resultStr);
        String openid = result1.getString("openid");
        if (null == openid || "".equals(openid)) {
            result.put("code", 1);
            result.put("desc", result1.toString());
            return result;
        }
        String BindOpenid = "weixinsmall_" + result1.getString("openid");
        //查询小程序用户的openid 如果不存在就是当前用户是新用户 允许自动登录
        String bindId = userServiceClient.selectUserIdByOpenid(BindOpenid);
        if (null == bindId || "".equals(bindId)) {
            result.put("code", 1);
            result.put("desc", result1.toString());
            return result;

        } else {
            //如果不是新用户查询他的是否允许自动登录
            Integer integer = userServiceClient.queryAutoLogin(openid);
            //1 允许自动登录  2  不允许自动登录
            if(null == integer && 1 == integer){
                integer = 1;
            }
            result.put("code", 1);
            result.put("autoLogin", integer);
            result.put("desc", result1.toString());
            return result;
        }
    }

    @Override
    public Map<String, Object> paymentAuthorization(Map<String, String> paraMap) throws UnsupportedEncodingException {
        String shopId = paraMap.get("shopId");
        String token = paraMap.get("token");
        Map<String, Object> result = new HashMap<String, Object>();
        //初始化 小程序授权参数
        initWXPayConfig(shopId);
        UserInfoVO userInfoVO= ParseTokenUtils.getPlatformUser(token);
        if(null == userInfoVO){
            result.put("code","2");
            result.put("desc","token无效，请重新获取");
            return result;
        }
        String strUrl = String.format(WXPayConfig.getCODE_SESSION(), paraMap.get("code"));
        String resultStr = restTemplate.getForObject(strUrl, String.class);
        resultStr = new String(resultStr.getBytes("ISO-8859-1"), "UTF-8");
        JSONObject result1 = JSONObject.parseObject(resultStr);
        String openid = result1.getString("openid");
        result.put("openid", result1.getString("openid"));
        result.put("session_key", result1.getString("session_key"));
        userInfoVO.setBindOpenid(openid);

        RedisUtil.set(YFConfig.YF_USER_TOKEN_USER + token, JSON.toJSONString(userInfoVO),
                YFConfig.TOKEN_OUTTIME);
        RedisUtil.set(YFConfig.YF_USER_TOKEN_USERID + token, userInfoVO.getUserId().toString(),
                YFConfig.TOKEN_OUTTIME);

        result.put("code","1");
        result.put("desc","");
        return result;
    }

    @Override
    public ResponseResult weixinOut(Map<String, String> paraMap) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(paraMap.get("token"));
        if (null == userInfo) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL.getCode(), BizCodeEnume.TOKEN_IS_ILLEGAL.getMsg());
        }
        if(null != userInfo && null != userInfo.getBindOpenid()){
            //手动退出 当前登录微信小程序的用户 下次不会自动登录小程序
            Map<String,Object> paramMap = new HashMap<>();
            paramMap.put("openid",userInfo.getBindOpenid());
            paramMap.put("start",2);//1 是允许自动登录 2 是不允许自动登录
            userServiceClient.updateAotuLogin(paramMap);
            RedisUtil.remove(YFConfig.YF_USER_TOKEN_USER + paraMap.get("token"));
        }
        return ResponseResult.success();
    }

    @Override
    public ResponseResult userLogoff(Map<String, String> paraMap) {
        String token = paraMap.get("token");
        String json = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER + token);
        if (null == json || "".equals(json)) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        try {
            UserInfoVO userInfo = ParseTokenUtils.getUserInfoByTokenNoIsExist(token);
            // 删除用户信息
            userServiceClient.delUserInfo(userInfo.getUserId());
            //删除微客信息
            payMentServiceClient.delFxInfo(userInfo.getUserId());
            //删除店铺信息
            if(null != userInfo.getShopId()){
                Map<String,String> map = new HashMap<>();
                map.put("shopId",userInfo.getShopId());
                map.put("userId",userInfo.getUserId());
                businessServiceClient.delShopInfo(map);
            }
            RedisUtil.remove(YFConfig.YF_USER_TOKEN_USER + token);
            return ResponseResult.success(1,  "注销成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.fail(2, "未知的用户信息");
    }
}
